﻿using Extented.UI.Core.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Media;

namespace Extented.UI.Core.Native
{
    public abstract class RenderControlBase : FrameworkRenderElement
    {
        protected abstract FrameworkElement CreateFrameworkElement(FrameworkRenderElementContext context);
        protected override void InitializeContext(FrameworkRenderElementContext context)
        {
            var controlContext = (RenderControlBaseContext)context;
            controlContext.Control = CreateFrameworkElement(context);
            controlContext.UpdateControlForeground();
            base.InitializeContext(context);
        }
        protected override Size MeasureOverride(Size availableSize, IFrameworkRenderElementContext context)
        {
            RenderControlBaseContext controlContext = (RenderControlBaseContext)context;
            var control = controlContext.Control;
            if (control == null)
                return new Size();
            control.Measure(availableSize);
            return control.DesiredSize;
        }
        protected override Size ArrangeOverride(Size finalSize, IFrameworkRenderElementContext context)
        {
            RenderControlBaseContext controlContext = (RenderControlBaseContext)context;
            var control = controlContext.Control;
            if (control == null)
                return finalSize;
            if (!Equals(control.RenderSize, finalSize))
                controlContext.UpdateLayout(FREInvalidateOptions.AffectsVisual);
            control.Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height));
            return finalSize;
        }
        protected override void RenderOverride(DrawingContext dc, IFrameworkRenderElementContext context)
        {
            base.RenderOverride(dc, context);
            var freContext = (RenderControlBaseContext)context;
            var transform = freContext.GeneralTransform;
            var control = freContext.Control;
            if (control == null)
                return;
            var vto = control as IVisualTransformOwner;
            if (vto != null)
                vto.VisualTransform = transform;
            else
                RenderTriggerHelper.SetValue(control, "VisualTransform", transform, BindingFlags.Instance | BindingFlags.NonPublic);
        }
    }
}
